﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

namespace Assets.Custom_Scripts
{
    public class CountdownTimer : MonoBehaviour
    {

        public float TimeAllowed = 100.0f;
        public float TimeLeft = 100.0f;
        public string TimeOutEvent;
        public GameObject Parent;

        protected bool _startedCounting = false;

        public void Start()
        {
            TimeLeft = TimeAllowed;

            if (null == Parent)
            {
                throw new System.Exception(@"Drag the GameObject this script is attached to into the Parent field.");
            }
            if (string.IsNullOrEmpty(TimeOutEvent))
            {
                throw new System.Exception(@"Type in a method in the Parent GameObject to call when the timer runs out.");
            }
        }

        public void BeginCounting()
        {
            TimeLeft = TimeAllowed;
            _startedCounting = true;
        }

        public void StopCounting()
        {
            _startedCounting = false;
        }


        public void Update()
        {
            if (!_startedCounting)
            {
                return;
            }

            TimeLeft -= Time.deltaTime;

            if (TimeLeft <= 0)
            {
                TimeLeft = 0;
                ExitRoutine();
            }
        }

        public void ExitRoutine()
        {
            if (null == Parent)
            {
                return;
            }
            if (string.IsNullOrEmpty(TimeOutEvent))
            {
                return;
            }

            _startedCounting = false;
            Parent.SendMessage(TimeOutEvent);

        }

        public float CheckTime()
        {
            return TimeLeft;
        }


    }
}
